#!/usr/bin/perl
#use warnings;

$STRING='("[^"]*")';
$COMMENT = '((?:\/\*(?:[^*]|(?:\*+[^*\/]))*\*+\/)|(?:\/\/.*))';

#source file partern
$SRC_PARTERN = '*.[ch]';
$OUT_COMMENT_EXT = '.cmt';
$OUT_STRING_EXT = '.str';
#output dir
$OUT_DIR = 'G:/Work/output';
$INPUT_FILE = '/cygdrive/g/Work/kinetis.c';

if(($#ARGV + 1) > 0) {
    $INPUT_FILE = $ARGV[0];
    print "Input file: $INPUT_FILE \n";
}

@lines = ();

sub countLine;
sub myseperate;

sub myseperate(){
	my $file_path = $INPUT_FILE;
	if (@_ > 0) {
		($file_path) = @_; 
    }
    my $cmt_path = $file_path.$OUT_COMMENT_EXT;
    my $str_path = $file_path.$OUT_STRING_EXT;
    #print "file: $file_path\n";
    #print "cmt: $cmt_path\n";
    #print "str: $str_path\n";
    #Read content of file
    open(TXT, $file_path) or die("Could not open $file_path.\n");
    $contents = "";
  	while($line = <TXT>){
  	  	$contents .= $line;
        @lines = (@lines, $line);
  	}
    #close file
  	close(TXT);
    
    #open comment file to write:
    open (CMT, "+>".$cmt_path) or die("Could not open $cmt_path to write.\n");
    open (STR, "+>".$str_path) or die("Could not open $str_path to write.\n");
    
    #print $contents;
    #print "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nlines:". @lines ."\n\n";
    
    while( $contents =~ m/$COMMENT/g ){
    	$po = $-[0];
    	print CMT "~~~~~~~~~~~~~~~~~~~~~~~~line: ".countLine($po)."\n$1\n\n";
    }
    
    #remove comment
    #$contents =~ s/$COMMENT//g;
    
    #remove #define and #include
    #$contents =~ s/(#.*)//g;
    
    #find strings
    while ( $contents =~ m/$STRING/g ) {
    	print STR "===========================line: " .countLine($-[0])."\n$1\n\n";
    }
    
    #remove strings
    #$contents =~ s/$STRING//g;
    
    #print $contents;
    
    #close all files
    close(CMT);
    close(STR);
}

sub countLine{
	my ($pos) = @_; 
    my $p=0;
    my $i=0; 
    while($p<$pos){
    	$l = @lines[$i];
        $p += length($l);
        $i++;
    }
    
    return $i;
}

myseperate();